package com.youdianstar.app.ui.account

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import android.widget.TextView

import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityProfileBinding
import com.youdianstar.app.entity.AccountEdit
import com.youdianstar.app.entity.UserCenterResponse
import com.youdianstar.app.support.imp.IOnEditListener
import com.youdianstar.app.support.imp.IProfileEditListener
import com.youdianstar.app.util.AppDialogUtil
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.PHOTO_ALBUM
import com.youdianstar.app.common.PHOTO_CAMERA
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.FileUpResult
import com.youdianstar.app.common.entity.UserInfo
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.DateUtil
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.common.util.dialog.DialogUtil
import com.chivorn.picker.DateTimePickerView
import com.safframework.eventbus.EventBus
import com.safframework.eventbus.UI
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.entity.BusEntity
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.common.auko.startActivityForResult
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.*


/**
 * File: ProfileActivity
 * Author: 82149 Create: 2021/10/8 17:53
 * Changes (from 2021/10/8)
 * --------------------------------------------------
 * description: 个人中心
 * ---------------------------------------------------
 *
 */
class ProfileActivity : BaseActivity<ActivityProfileBinding, LoginViewModel>() {
    override fun layoutId(): Int = R.layout.activity_profile

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): LoginViewModel {
        val model: LoginViewModel by viewModel()
        return model
    }

    private val mHandler = Handler(Looper.myLooper()!!)
    private var isRefresh = false
    private lateinit var genderList: List<String>

    private var selectType: Int = 0
    private var userInfo: UserInfo? = null
    private var editReq = AccountEdit(id = 0)

    private lateinit var editListener: ProfileEditListener
    private val REQUEST_CODE = 0x18
    private var phoneDialog : Dialog? =null
    private var emailDialog : Dialog? =null

    override fun initData() {
        super.initData()
        EventBus.register(this.javaClass.simpleName, UI, BusEntity::class.java) {
            if (it.code ==  DataCode.PUSH_UPDATE){
                isRefresh = true
            }
        }
        mBinding.headBar.initTitle(this, getString(R.string.profile_profile)) {
            //Save local user
        }
        userInfo = DataAppManager.instance.getUser()
        userInfo?.let {
            LogUtil.i("---User:$userInfo")
            LogUtil.i("---User Details: id=${it.id}, code=${it.code}, phone=${it.phone}, email=${it.email}, nickname=${it.nickname}, uid=${it.uid}")
            setUserLayout(it)
        }
        genderList = listOf(
            getString(R.string.profile_male),
            getString(R.string.profile_female),
            getString(R.string.profile_secret)
        )
        editListener = ProfileEditListener()
        loadAccount()
    }

    override fun onResume() {
        super.onResume()
        if (isRefresh){
            loadAccount()
            isRefresh = false
        }
    }

    private fun loadAccount() {
        mHandler.postDelayed({
            mViewModel.getAccount()
        }, 300L)
    }

    override fun initClickEvent() {
        mBinding.clHeadContainer.setThrottleListener {
            showPhotoDialog()
        }
        mBinding.rlName.setThrottleListener {
            showNicknameDialog()
        }

        mBinding.rlGender.setThrottleListener {
            showGanderDialog()
        }

        mBinding.rlBirth.setThrottleListener {
            checkAndShowPickerDialog()
        }

        mBinding.rlPhone.setThrottleListener {
            // TODO: 暂时屏蔽手机号码跳转功能，待后续处理
            /*
            userInfo?.let {
                if (StrUtil.isEmpty(it.phone)){
                    startActivity<ChangeStep2Activity>(Extra.IT_TYPE to 0,Extra.IT_Link to true)
                }else{
                    startActivity<ChangeStep1Activity>(Extra.IT_TYPE to 0)
                }
            }
            */
        }

        mBinding.rlEmail.setThrottleListener {
            // TODO: 暂时屏蔽邮箱跳转功能，待后续处理
            /*
            userInfo?.let {
                if (StrUtil.isEmpty(it.email)){
                    startActivity<ChangeStep2Activity>(Extra.IT_TYPE to 1,Extra.IT_Link to true)
                }else{
                    startActivity<ChangeStep1Activity>(Extra.IT_TYPE to 1)
                }
            }
            */
        }

        mBinding.rlReceipt.setThrottleListener {
            showReceiptEmailDialog()
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.timeCountEvent.observe(this, androidx.lifecycle.Observer {
            editListener.setCountTime(it)
        })

        mViewModel.otpResultLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mViewModel.onOtpSuccess()
                mViewModel.downCount()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.fileUploadLiveData.observe(this, object : BaseApiResultObserver<FileUpResult>(false) {
                override fun onDataResult(data: FileUpResult?) {
                    super.onDataResult(data)
                    data?.let {
                        editReq.clean()
                        editReq.icon = it.value
                        mViewModel.edtAccount(editReq)
                    }
                }
            })

        mViewModel.editResultLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                loadAccount()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.editNicknameLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                toastShow("昵称修改成功")
                // 修改成功后重新获取用户信息并更新全局
                loadAccount()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e ?: "修改失败")
            }
        })

        mViewModel.userCenterResultLiveData.observe(this, object : BaseApiResultObserver<UserCenterResponse>(false) {
            override fun onDataResult(data: UserCenterResponse?) {
                LogUtil.d("ProfileActivity", "onDataResult被调用: data=$data")
                super.onDataResult(data)
                dismissDialog()
                data?.let { userCenterResponse ->
                    val it = userCenterResponse.user // 从UserCenterResponse中提取user信息
                    LogUtil.i("---UserCenterInfo: id=${it.id}, countryCode=${it.countryCode}, mobile=${it.mobile}, email=${it.email}, nickName=${it.nickName}")
                    
                    // 获取当前用户信息作为基础，如果为null则创建一个新的
                    val currentUser = userInfo ?: DataAppManager.instance.getUser()
                    
                    if (currentUser != null) {
                        // 更新用户信息字段
                        currentUser.code = it.countryCode
                        currentUser.phone = it.mobile
                        currentUser.email = it.email
                        currentUser.receiptEmail = it.email // UserCenterInfo没有receiptEmail字段，使用email
                        currentUser.icon = it.avatar
                        currentUser.nickname = it.nickName
                        currentUser.birthday = it.birthday
                        currentUser.sex = it.sex
                        currentUser.google = false // UserCenterInfo没有google字段，使用默认值
                        currentUser.isBranch = false // UserCenterInfo没有isBranch字段，使用默认值
                        
                        LogUtil.i("---Updated UserInfo: id=${currentUser.id}, code=${currentUser.code}, phone=${currentUser.phone}, email=${currentUser.email}, nickname=${currentUser.nickname}")
                        
                        // 更新UI和保存数据
                        setUserLayout(currentUser)
                        DataAppManager.instance.saveUser(currentUser)
                        // 更新本地userInfo引用
                        this@ProfileActivity.userInfo = currentUser
                    } else {
                        LogUtil.e("---UserInfo is null, cannot update data")
                    }
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                LogUtil.e("---UserCenter API Error: code=$code, error=$e")
                toastShow(e)
            }
        })
    }

    private fun setUserLayout(user: UserInfo) {
        LogUtil.i("---setUserLayout: phone=${user.phone}, email=${user.email}, code=${user.code}")
        LogUtil.i("---setUserLayout full user: $user")
        
        editReq.run {
            id = user.id
            code = user.code
            phone = user.phone
            email = user.email
            receiptEmail = user.receiptEmail
            nickname = user.nickname
            sex = user.sex
        }
        val formatUid = StrUtil.format8LenStr(user.uid)
        mBinding.tvUidValue.text = if (user.uid==0) "" else "U$formatUid"
        mBinding.tvBirthdayValue.text = if (!StrUtil.isEmpty(user.birthday)) user.birthday else getString(R.string.profile_picker_title)

        val genderStr = when (user.sex) {
            0 -> getString(R.string.profile_female)
            1 -> getString(R.string.profile_male)
            2 -> getString(R.string.profile_secret)
            else->{
                getString(R.string.profile_select)
            }
        }
        mBinding.tvGenderValue.text = genderStr

        // 设置邮箱显示
        val emailText = if (!StrUtil.isEmpty(user.email)) user.email else "xxx@xxx.com"
        mBinding.tvEmailValue.text = emailText
        LogUtil.i("---setUserLayout email: ${user.email} -> $emailText")
        
        // 设置手机号显示
        if (null==user.code || StrUtil.isEmpty(user.phone)){
            mBinding.tvPhoneValue.text = "--"
            LogUtil.i("---setUserLayout phone: code=${user.code}, phone=${user.phone} -> --")
        }else{
            // 检查code是否是有效的区号（区号通常是1-999之间的数字，如果大于999可能是用户ID）
            val countryCode = user.code
            val isValidCountryCode = countryCode != null && countryCode > 0 && countryCode <= 999
            if (isValidCountryCode) {
                // 有效的区号，显示 +区号 手机号
                val phoneText = String.format(getString(R.string.profile_hold_Phone), countryCode, user.phone)
                mBinding.tvPhoneValue.text = phoneText
                LogUtil.i("---setUserLayout phone: code=${countryCode}, phone=${user.phone} -> $phoneText")
            } else {
                // 无效的区号（可能是用户ID），只显示手机号，去掉+
                mBinding.tvPhoneValue.text = user.phone
                LogUtil.i("---setUserLayout phone: code=${countryCode} (invalid, looks like user ID), phone=${user.phone} -> ${user.phone}")
            }
        }
        mBinding.tvReceiptEmail.text = if (!StrUtil.isEmpty(user.receiptEmail)) user.receiptEmail else "xxx@xxx.com"
        
        // 设置昵称显示
        mBinding.tvNameValue.text = if (!StrUtil.isEmpty(user.nickname)) user.nickname else "--"
        
        //Google 账号判断
        mBinding.rlGoogleSign.visibility = if (user.google) View.VISIBLE else View.INVISIBLE
        mBinding.lineGoogle.visibility = if (user.google) View.VISIBLE else View.INVISIBLE
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        if (requestCode == REQUEST_PERMISSION_CODE)
            showPhotoPicker(selectType)
    }

    /**
     * 图片选择
     * @param type 类型
     */
    private fun showPhotoPicker(type: Int) {
        startSLImagePicker(this, type = type, needCrop = true) { path ->
            mViewModel.upLoadImage(path)
        }
    }

    /**
     * 图片选择器
     */
    private fun showPhotoDialog() {
        DialogUtil.instance.showSelectDialog(this) { selectIndex ->
            selectType = selectIndex
            when (selectIndex) {
                PHOTO_CAMERA -> requestCameraPermission {
                    showPhotoPicker(PHOTO_CAMERA)
                }
                PHOTO_ALBUM -> requestAlbumPermission {
                    showPhotoPicker(PHOTO_ALBUM)
                }
            }
        }
    }

    /**
     * 编辑邮箱
     * --票据邮箱
     */
    /**
     * 编辑昵称
     */
    private fun showNicknameDialog() {
        AppDialogUtil.instance.showEditDialog(this,
            title = "修改昵称",
            hintText = "请输入昵称",
            defaultName = userInfo?.nickname,
            edtType = 1,
            rightAction = { nickname ->
                val userId = userInfo?.id ?: 0
                if (userId > 0) {
                    mViewModel.editNickname(userId, nickname)
                } else {
                    toastShow("用户ID无效")
                }
            },
            left = getString(R.string.public_cancel),
            right = getString(R.string.profile_confirm)
        )
    }

    private fun showReceiptEmailDialog(){
        AppDialogUtil.instance.showEditDialog(this,
            title = getString(R.string.profile_emailReceiving),
            hintText = getString(R.string.toast_requiredEmail),
            defaultName = userInfo?.receiptEmail, edtType = 2,
            rightAction = {
                editReq.clean()
                editReq.receiptEmail = it
                mViewModel.edtAccount(editReq)
            }, left = getString(R.string.public_cancel), right = getString(R.string.profile_confirm)
        )
    }

    private fun showGanderDialog(){
        var defaultIndex = -1
        userInfo?.let {
            when(it.sex){
                0-> defaultIndex = 1
                1-> defaultIndex = 0
                2-> defaultIndex = 2
            }
        }
        // sex 0-女 1-男 2-其他 3-未设置
        // index 0 男 1 女 2 第三类
        AppDialogUtil.instance.showGenderDialog(this, genderList,defaultP = defaultIndex) {
            if (it!=-1){
                editReq.clean()
                when (it) {
                    0 -> editReq.sex = 1
                    1 -> editReq.sex = 0
                    else -> editReq.sex = 2
                }
                mViewModel.edtAccount(editReq)
            }
        }
    }

    private var dtpvCustomLunar: DateTimePickerView? = null
    private val picker = booleanArrayOf(true, true, true, false, false, false)

    private fun checkAndShowPickerDialog(){
        if (!StrUtil.isEmpty(userInfo?.birthday)) {
            var date: Date? = null
            try {
                val birthStr = StrUtil.parseAllSpace(userInfo?.birthday)
                date = DateUtil.getDateByFormat(birthStr, DateUtil.DMY_BRS)
                if (date == null)
                    date = DateUtil.getDateByFormat(birthStr, DateUtil.MDY_BRS)
            } catch (_: Exception) {
            }
            date?.let {
                showPickerDialog(it)
            }
        } else {
            showPickerDialog(Date())
        }
    }

    /**
     * 显示时间选择器
     *
     * @param selectLong
     */
    private fun showPickerDialog(selectLong: Date) {
        val selectedDate = Calendar.getInstance()//系统当前时间
        selectedDate.time = selectLong
        val endDate = Calendar.getInstance()
        endDate.time = Date()
        val startDate = Calendar.getInstance()
        startDate.set(endDate.get(Calendar.YEAR) - 130, 0, 1)
        //时间选择器 ，自定义布局
        if (null != dtpvCustomLunar)
            dtpvCustomLunar = null
        dtpvCustomLunar = DateTimePickerView.Builder(this, object : DateTimePickerView.OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                    val dateStr = DateUtil.getProjectTime(date, DateUtil.DMY_BRS)
                    editReq.clean()
                    editReq.birthday = dateStr
                    mViewModel.edtAccount(editReq)
                }
            }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setNumberModel(true)
                .setType(picker)
                .isCenterLabel(false)
                .setLayoutRes(R.layout.layout_picker_date) { v ->
                    val tvTitle = v?.findViewById(R.id.tvTitle) as TextView
                    val btnCancel = v.findViewById(R.id.btnCancel) as Button
                    val btnSubmit = v.findViewById(R.id.btnSubmit) as Button
                    tvTitle.text = getString(R.string.profile_picker_title)
                    tvTitle.setOnClickListener {  }
                    btnCancel.setOnClickListener {
                        dtpvCustomLunar?.dismiss()
                    }
                    btnSubmit.setOnClickListener {
                        dtpvCustomLunar?.returnData()
                        dtpvCustomLunar?.dismiss()
                    }
                }
                .setDividerColor(Color.LTGRAY)
                .build()
        dtpvCustomLunar?.setOnDismissListener { }
        dtpvCustomLunar?.show()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null!=phoneDialog && phoneDialog?.isShowing == true)
            phoneDialog?.dismiss()
        if (null!=emailDialog && emailDialog?.isShowing == true)
            emailDialog?.dismiss()
        editListener.onDismiss()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            val codeValue = data?.getStringExtra(Extra.IT_CODE)
            codeValue?.let {
                editListener.setCountryCode(it)
            }
        }
    }



    /*****************************************修改手机+邮箱******************************************/

    /**
     * 编辑邮箱
     * --旧版
     */
    private fun showEditEmailDialog(){
        if (null!=emailDialog && emailDialog?.isShowing == true){
            emailDialog?.dismiss()
            emailDialog = null
        }
        emailDialog = AppDialogUtil.instance.showEditEmailDialog(this,editListener,object : IOnEditListener {
            override fun onEditAccount(account: String, code: String,msgCode : String) {
                LogUtil.i("-----save :$account,$code;$msgCode")
                editReq.clean()
                editReq.email = account
                editReq.msgCode = msgCode
                mViewModel.edtAccount(editReq)
            }
        })
    }

    /**
     * 编辑手机号
     * --旧版
     */
    private fun showEditPhoneDialog(){
        if (null!=phoneDialog && phoneDialog?.isShowing == true){
            phoneDialog?.dismiss()
            phoneDialog = null
        }
        phoneDialog = AppDialogUtil.instance.showEditPhoneDialog(this,editListener,object :
            IOnEditListener {
            override fun onEditAccount(account: String, code: String,msgCode : String) {
                LogUtil.i("-----save :$account,$code;$msgCode")
                editReq.clean()
                editReq.phone = account
                editReq.code = code.toInt()
                editReq.msgCode = msgCode
                mViewModel.edtAccount(editReq)
            }
        })
    }

    inner class ProfileEditListener : IProfileEditListener {
        var tvCountry: TextView? = null
        var tvCount: TextView? = null
        //国家码
        var codeValue: String = ""

        override fun setCountView(view: TextView) {
            tvCount = view
        }

        override fun setCountryView(view: TextView) {
            tvCountry = view
            val countryCode = DataAppManager.instance.getPhoneCode()
            setCountryCode(countryCode)
        }

        override fun onDismiss() {
            tvCountry = null
            tvCount = null
        }

        override fun selectCountryAction() {
            startActivityForResult<PhoneCodeActivity>(requestCode = REQUEST_CODE)
        }

        override fun getOtpAction(accountStr: String, type: String) {
            val phoneStr: String? = if (StrUtil.isEmpty(type)) null else accountStr
            val countryCode:String? = if (StrUtil.isEmpty(type)) null else codeValue
            val email: String? = if (StrUtil.isEmpty(type)) accountStr else null
            if ((!StrUtil.isEmpty(countryCode) && !StrUtil.isEmpty(phoneStr)) || !StrUtil.isEmpty(email)){
                mViewModel.getEditPhoneOTP(countryCode, phoneStr, email)
            }
        }

        override fun setCountTime(count: Long) {
            if (count == -1L) {
                tvCount?.isEnabled = true
                tvCount?.text = getString(R.string.login_get)
            } else {
                var time = "$count"
                if (time.length == 1) {
                    time = "0$count"
                }
                tvCount?.isEnabled = false
                tvCount?.text = time+"s"
            }
        }

        override fun setCountryCode(code: String) {
            codeValue = code
            tvCountry?.text = "+$codeValue"
        }

        override fun getCountryCode(): String {
            return codeValue
        }

    }
}